package com.ship.dispatch.service.fob.impl;
/**
 *@title SpFobZzgcjrServiceImpl
 *@description 装载港船岸兼容
 *@author yl
 *@create 2023/12/13 0013
 */

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ship.common.core.exception.BusException;
import com.ship.common.core.utils.StringUtils;
import com.ship.common.core.web.domain.BaseResultCode;
import com.ship.common.security.utils.SecurityUtils;
import com.ship.dispatch.bean.SpDispatchSchemeExecute;
import com.ship.dispatch.bean.fob.*;
import com.ship.dispatch.bo.SpBoatsActualCompatibleBo;
import com.ship.dispatch.bpm.utils.JsonUtils;
import com.ship.dispatch.bpm.utils.TemplateParamUtils;
import com.ship.dispatch.bpm.vo.ManageEntityVo;
import com.ship.dispatch.mapper.fob.SpFobSalesZzgcjrMapper;
import com.ship.dispatch.mapper.fob.SpFobZzgcjrMapper;
import com.ship.dispatch.service.SpBoatsActualCompatibleService;
import com.ship.dispatch.service.SpDispatchSchemeExecuteService;
import com.ship.dispatch.service.fob.SpFobFileRecordService;
import com.ship.dispatch.service.fob.SpFobSalesZzgcjrService;
import com.ship.dispatch.service.fob.SpFobTemplateService;
import com.ship.dispatch.service.fob.SpFobZzgcjrService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class SpFobSalesZzgcjrServiceImpl extends FobBaseServiceImpl<SpFobSalesZzgcjrMapper, SpFobSalesZzgcjr> implements SpFobSalesZzgcjrService {

    @Autowired(required = false)
    SpFobSalesZzgcjrMapper spFobZzgcjrMapper;

    @Autowired
    SpFobFileRecordService spFobFileRecordService;
    @Autowired
    SpDispatchSchemeExecuteService schemeDetailService;
    @Autowired
    SpFobTemplateService spFobTemplateService;

    @Override
    public void updateEntity(ManageEntityVo manageEntityVo, String json) {
        SpFobSalesZzgcjr object = JsonUtils.jsonToObject(json,SpFobSalesZzgcjr.class);
        SpFobSalesZzgcjr his = spFobZzgcjrMapper.selectOne(new LambdaQueryWrapper<SpFobSalesZzgcjr>().eq(SpFobSalesZzgcjr::getProceeInstanceId,manageEntityVo.getProcessInstanceId()).ne(SpFobSalesZzgcjr::getStatus,-2));
        if(manageEntityVo.getOperationType()==1) {
            object.setStatus(1);
        }
        if(his==null){ // 新增
            object.setSchemeDetailId(manageEntityVo.getSchemeDetailId());
            object.setProceeInstanceId(manageEntityVo.getProcessInstanceId());
            object.setTaskId(manageEntityVo.getTaskId());
            spFobZzgcjrMapper.insert(object);
        }else { // 修改
            object.setId(his.getId());
            BeanUtils.copyProperties(object,his);
            spFobZzgcjrMapper.updateById(his);
            // 处理多余文件记录
            his = spFobZzgcjrMapper.selectOne(new LambdaQueryWrapper<SpFobSalesZzgcjr>().eq(SpFobSalesZzgcjr::getProceeInstanceId,manageEntityVo.getProcessInstanceId()).ne(SpFobSalesZzgcjr::getStatus,-2));
            List<String> ids = new ArrayList<>();
            if((his.getFiels()!=null && his.getFiels().length()>0) || his.getSccfiels()!=null && his.getSccfiels().length()>0){
                String temp = his.getFiels();
                if(temp==null || temp.length()==0){
                    temp =  his.getSccfiels();
                }else if( his.getSccfiels()!=null){
                    temp = temp +"," + his.getSccfiels();
                }
                String[] fieldIds = temp.split(",");
                ids =  Arrays.stream(fieldIds).collect(Collectors.toList());
                //ids.retainAll(Collections.singleton(null));
            }
            spFobFileRecordService.deleteOtherFileRecor(his.getId(),ids);
        }
    }

    @Override
    public SpFobBaseBean getBaseBeanByInstanceId(String id) {
        return spFobZzgcjrMapper.selectOne(new LambdaQueryWrapper<SpFobSalesZzgcjr>().eq(SpFobSalesZzgcjr::getProceeInstanceId,id).ne(SpFobSalesZzgcjr::getStatus,-2));
    }
    @Override
    public void  saveEntity(SpFobBaseBean bean){
        SpFobSalesZzgcjr spFobZzgcjr = new SpFobSalesZzgcjr();
        BeanUtils.copyProperties(bean,spFobZzgcjr);
        this.save(spFobZzgcjr);
    }

    @Override
    public void updateEntityById(SpFobBaseBean bean) {
        SpFobSalesZzgcjr spFobZzgcjr = new SpFobSalesZzgcjr();
        BeanUtils.copyProperties(bean,spFobZzgcjr);
        this.updateById(spFobZzgcjr);
    }

    @Override
    public Object getFormData(String id,Long serviceId) {
        SpFobSalesZzgcjr spFobZzgcjr = null;
        if(serviceId!=null){
            spFobZzgcjr = spFobZzgcjrMapper.selectById(serviceId);
        }else {
            spFobZzgcjr = spFobZzgcjrMapper.selectOne(new LambdaQueryWrapper<SpFobSalesZzgcjr>().eq(SpFobSalesZzgcjr::getProceeInstanceId,id).ne(SpFobSalesZzgcjr::getStatus,-2));
        }
        if(spFobZzgcjr==null){
            return null;
        }
        Map<String,Object> map = JsonUtils.jsonToMap(JsonUtils.objectToJson(spFobZzgcjr), Object.class);
        if(StringUtils.isNotBlank(spFobZzgcjr.getFiels())){
            String[] ids = spFobZzgcjr.getFiels().split(",");
            List<Long> resId = new ArrayList<>();
            for(String tempId:ids){
                if (StringUtils.isNotBlank(tempId)) {
                    resId.add(Long.parseLong(tempId));
                }
            }
            List<SpFobFileRecord> spFobFileRecordList =  spFobFileRecordService.listByIds(resId);
            map.put("fiels",spFobFileRecordList);
        }
        if(StringUtils.isNotBlank(spFobZzgcjr.getSccfiels())){
            String[] ids = spFobZzgcjr.getFiels().split(",");
            List<Long> resId = new ArrayList<>();
            for(String tempId:ids){
                if (StringUtils.isNotBlank(tempId)) {
                    resId.add(Long.parseLong(tempId));
                }
            }
            List<SpFobFileRecord> spFobFileRecordList =  spFobFileRecordService.listByIds(resId);
            map.put("sccfiels",spFobFileRecordList);
        }
        SpDispatchSchemeExecute execute = schemeDetailService.getExceuteByInstanceId(spFobZzgcjr.getProceeInstanceId());
        if (execute.getExpectedLoadingPort()!=null && spFobZzgcjr.getPort() == null){
            map.put("port",execute.getExpectedLoadingPort());
        }
        if (spFobZzgcjr.getField2() == null){
            map.put("field2", "是");
        }
        return map;
    }
    @Override
    public String  getTemplateParam(ManageEntityVo manageEntityVo) {
        SpDispatchSchemeExecute schemeDetail = schemeDetailService.getExceuteByInstanceId(manageEntityVo.getProcessInstanceId());
        Map<String,String> map = new HashMap<>();
        if(schemeDetail!=null){
            Map<String,String> tempMap = JsonUtils.jsonToMap(JsonUtils.objectToJson(schemeDetail),String.class);
            for(String key:tempMap.keySet()){
                map.put("spDispatchSchemeDetail."+key,tempMap.get(key));
            }
        }
        ObjectNode json = manageEntityVo.getData();
        if(json!=null){
            Map<String,String> tempMap = JsonUtils.jsonToMap(JsonUtils.objectToJson(json),String.class);
            for(String key:tempMap.keySet()){
                map.put("spFobSalesZzgcjr."+key,tempMap.get(key));
            }
            // 默认发件人 当前登录用户
            map.put("spFobSalesZzgcjr.sendRecipient", SecurityUtils.getUsername());
        }
        SpFobZzgcjr spFobZzgcjr = JsonUtils.jsonToObject(JsonUtils.objectToJson(json),SpFobZzgcjr.class);
        String templateId = null;
        if("FOB002-01-01".equals(manageEntityVo.getFormKey())){
            templateId = spFobZzgcjr.getTemplateId();
        }else {
            templateId = spFobZzgcjr.getSccTemplateId();
        }
        if(templateId==null){
            throw  new BusException("请选模板后再生成模板正文", BaseResultCode.GENERAL_ERROR);
        }
        SpFobTemplate spFobTemplate = spFobTemplateService.getById(templateId);
        String template = "";
        if(spFobTemplate !=null){
            template = TemplateParamUtils.processDynamicParams(spFobTemplate.getContent(),map);
        }
        return template;
    }

    @Override
    public List<Long> findServieData(String processInstanceId){
        List<SpFobSalesZzgcjr> spFobBaseBeans =  spFobZzgcjrMapper.selectList(new LambdaQueryWrapper<SpFobSalesZzgcjr>().eq(SpFobSalesZzgcjr::getProceeInstanceId,processInstanceId).orderByDesc(SpFobSalesZzgcjr::getCreateDate));
        List<Long> list = spFobBaseBeans.stream().map(SpFobBaseBean::getId).collect(Collectors.toList());
        return list;
    }

    @Resource
    SpBoatsActualCompatibleService spBoatsActualCompatibleService;
    // 完成信息同步订单信息
    @Override
    public void createPayOrder(Long id) {
        SpFobSalesZzgcjr zzgcjr = this.getById(id);
        SpBoatsActualCompatibleBo boatsActualCompatibleBo = new SpBoatsActualCompatibleBo();
        SpDispatchSchemeExecute execute =  schemeDetailService.getExceuteByInstanceId(zzgcjr.getProceeInstanceId());
        if(execute!=null){
            boatsActualCompatibleBo.setImo(execute.getImo());
            boatsActualCompatibleBo.setShipName(execute.getShipName());
            boatsActualCompatibleBo.setVoyageNo(execute.getVoyageNo());
            boatsActualCompatibleBo.setExpectedLoadingPort(execute.getExpectedLoadingPort());
            if(com.ship.dispatch.util.StringUtils.isNotBlank(zzgcjr.getPort())){
                boatsActualCompatibleBo.setExpectedLoadingPort(zzgcjr.getPort());
            }
            boatsActualCompatibleBo.setExpectedLoadingDate(execute.getExpectedLoadingDate());
            boatsActualCompatibleBo.setShipCompatibleDate(new Date());
            boatsActualCompatibleBo.setExpectedUnloadingPort(execute.getExpectedUnloadingPort());
            boatsActualCompatibleBo.setDispatchSchemeExecuteId(execute.getId());
            boatsActualCompatibleBo.setServiceId(id);
            boatsActualCompatibleBo.setPortType("1-装载港");
            boatsActualCompatibleBo.setIsShipShoreCompatibility(zzgcjr.getField2());
            spBoatsActualCompatibleService.synchronShipShoreCompatibility(boatsActualCompatibleBo);
        }
    }

}
